package com.example.teacherservice.service;

import com.example.teacherservice.dto.*;
import com.example.teacherservice.entity.Question;
import com.example.teacherservice.entity.Comment;
import com.example.teacherservice.entity.QuestionCollection;
import com.example.teacherservice.repository.QuestionRepository;
import com.example.teacherservice.repository.CommentRepository;
import com.example.teacherservice.repository.QuestionCollectionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class QuestionService {

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private QuestionCollectionRepository collectionRepository;

    public QuestionDTO createQuestion(QuestionRequest request) {
        Question question = new Question();
        question.setContent(request.getContent());
        question.setQuestionType(request.getQuestionType());
        question.setClassId(request.getClassId());

        if (request.getStudentId() != null) {
            question.setStudentId(request.getStudentId());
        } else if (request.getTeacherId() != null) {
            question.setTeacherId(request.getTeacherId());
        }

        question = questionRepository.save(question);
        return convertToQuestionDTO(question);
    }

    public QuestionDTO getQuestionById(Long id) {
        Question question = questionRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Question not found"));
        return convertToQuestionDTO(question);
    }

    public List<QuestionDTO> getAllQuestions() {
        return questionRepository.findByDeleted(0).stream()
                .map(this::convertToQuestionDTO)
                .collect(Collectors.toList());
    }

    public List<QuestionDTO> getQuestionsByStudentId(Long studentId) {
        return questionRepository.findByStudentIdAndDeleted(studentId, 0).stream()
                .map(this::convertToQuestionDTO)
                .collect(Collectors.toList());
    }

    public List<QuestionDTO> getQuestionsByTeacherId(Long teacherId) {
        return questionRepository.findByTeacherIdAndDeleted(teacherId, 0).stream()
                .map(this::convertToQuestionDTO)
                .collect(Collectors.toList());
    }

    public List<QuestionDTO> getQuestionsByClassId(Long classId) {
        return questionRepository.findByClassIdAndDeleted(classId, 0).stream()
                .map(this::convertToQuestionDTO)
                .collect(Collectors.toList());
    }

    public void deleteQuestion(Long id) {
        Question question = questionRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Question not found"));
        question.setDeleted(1);
        questionRepository.save(question);
    }

    public CommentDTO addComment(CommentRequest request) {
        // 验证问题是否存在
        if (!questionRepository.existsById(request.getQ_id())) {
            throw new RuntimeException("问题不存在");
        }

        // 验证必须有一个用户ID
        if (request.getStu_id() == null && request.getTea_id() == null) {
            throw new RuntimeException("必须提供学生ID或教师ID");
        }

        Comment comment = new Comment();
        comment.setQuestionId(request.getQ_id());
        comment.setContent(request.getContent());
        comment.setReplyId(request.getReply_id());

        // 设置用户类型
        if (request.getStu_id() != null) {
            comment.setStudentId(request.getStu_id());
        } else {
            comment.setTeacherId(request.getTea_id());
        }

        comment = commentRepository.save(comment);
        return convertToCommentDTO(comment);
    }

    public CommentDTO adoptComment(Long commentId) {
        Comment comment = commentRepository.findById(commentId)
                .orElseThrow(() -> new RuntimeException("Comment not found"));
        comment.setHasAdopt(1);
        comment = commentRepository.save(comment);
        return convertToCommentDTO(comment);
    }

    public void deleteComment(Long commentId) {
        Comment comment = commentRepository.findById(commentId)
                .orElseThrow(() -> new RuntimeException("Comment not found"));
        comment.setDeleted(1);
        commentRepository.save(comment);
    }

    public void collectQuestion(Long questionId, CollectionRequest request) {
        QuestionCollection collection = new QuestionCollection();
        collection.setStudentId(request.getStudentId());
        collection.setQuestionId(questionId);
        collection.setCollection(1);
        collectionRepository.save(collection);
    }

    private QuestionDTO convertToQuestionDTO(Question question) {
        QuestionDTO dto = new QuestionDTO();
        dto.setId(question.getId());
        dto.setContent(question.getContent());
        dto.setQuestionType(question.getQuestionType());
        dto.setClassId(question.getClassId());
        dto.setStudentId(question.getStudentId());
        dto.setTeacherId(question.getTeacherId());
        dto.setCreateTime(question.getCreateTime());
        dto.setLikeNum(question.getLikeNum());
        dto.setCollectionNum(question.getCollectionNum());
        return dto;
    }

    private CommentDTO convertToCommentDTO(Comment comment) {
        CommentDTO dto = new CommentDTO();
        dto.setId(comment.getId());
        dto.setQuestionId(comment.getQuestionId());
        dto.setContent(comment.getContent());
        dto.setStudentId(comment.getStudentId());
        dto.setTeacherId(comment.getTeacherId());
        dto.setLikeNum(comment.getLikeNum());
        dto.setCreateTime(comment.getCreateTime());
        dto.setIsAdopted(comment.getHasAdopt() == 1);
        dto.setReplyId(comment.getReplyId());
        return dto;
    }

    public List<CommentDTO> getCommentsByQuestionId(Long questionId) {
        // 1. 验证问题是否存在
        if (!questionRepository.existsById(questionId)) {
            throw new RuntimeException("Question not found with id: " + questionId);
        }

        // 2. 从数据库获取未删除的评论列表
        List<Comment> comments = commentRepository.findByQuestionIdAndDeleted(questionId, 0);

        // 3. 转换为DTO列表并返回
        return comments.stream()
                .map(this::convertToCommentDTO)
                .collect(Collectors.toList());
    }

    // 获取用户的问题列表(学生/教师通用)
    public List<UserQuestionDTO> getUserQuestions(Long userId) {
        return questionRepository.findByUserId(userId).stream()
                .map(question -> {
                    UserQuestionDTO dto = new UserQuestionDTO();
                    dto.setId(question.getId());
                    dto.setContent(question.getContent());
                    dto.setCreateTime(question.getCreateTime()); // 现在类型匹配
                    dto.setQuestionType(question.getQuestionType());
                    dto.setCommentCount(commentRepository.countByQuestionId(question.getId()));
                    dto.setIsStudent(question.getStudentId() != null);
                    return dto;
                })
                .collect(Collectors.toList());
    }

    // 获取用户的评论列表(学生/教师通用)
    public List<UserCommentDTO> getUserComments(Long userId) {
        return commentRepository.findByUserId(userId).stream()
                .map(comment -> {
                    UserCommentDTO dto = new UserCommentDTO();
                    dto.setId(comment.getId());
                    dto.setContent(comment.getContent());
                    dto.setCreateTime(comment.getCreateTime());
                    dto.setQuestionId(comment.getQuestionId());
                    dto.setIsStudent(comment.getStudentId() != null); // 标记是学生还是教师
                    dto.setIsAdopted(comment.getHasAdopt() == 1);
                    return dto;
                })
                .collect(Collectors.toList());
    }

    // 删除用户的问题(学生/教师通用)
    @Transactional
    public void deleteUserQuestion(Long questionId, Long userId) {
        // 1. 验证权限
        if (!questionRepository.isQuestionBelongsToUser(questionId, userId)) {
            throw new RuntimeException("问题不存在或无权删除");
        }

        // 2. 先删除相关评论
        questionRepository.deleteCommentsByQuestionId(questionId);

        // 3. 删除收藏记录
        questionRepository.deleteCollectionsByQuestionId(questionId);

        // 4. 软删除问题
        int deleted = questionRepository.softDeleteUserQuestion(questionId, userId);
        if (deleted == 0) {
            throw new RuntimeException("删除问题失败");
        }
    }


    @Transactional
    public void deleteUserComment(Long commentId, Long userId) {
        // 1. 验证权限
        if (!commentRepository.isCommentBelongsToUser(commentId, userId)) {
            throw new RuntimeException("无权删除此评论");
        }

        // 2. 先删除回复
        commentRepository.deleteReplies(commentId);

        // 3. 删除评论本身
        int deleted = commentRepository.deleteUserComment(commentId, userId);
        if (deleted == 0) {
            throw new RuntimeException("删除评论失败");
        }
    }

    public List<QuestionDTO> getQuestionsByUserId(Long userId) {
        return questionRepository.findByUserId(userId).stream()
                .map(this::convertToQuestionDTO)
                .collect(Collectors.toList());
    }
}